<?php

namespace app\admin\model\workteam;

use app\admin\library\Auth;
use app\admin\model\facrm\Customer;
use app\admin\model\facrm\Record;
use think\Exception;
use think\Model;
use think\Loader;

class Log extends Model
{

    // 表名
    protected $name = 'workteam_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = '';
    //自定义日志标题
    protected static $title = '';
    //自定义日志内容
    protected static $content = '';
    //忽略的链接正则列表
    protected static $ignoreRegex = [
        '/^(.*)\/(selectpage|index)$/i',
    ];
    // 追加属性
    protected $append = [
        'type_text','create_type_text','service_client_text'
    ];

    public static function setTitle($title)
    {
        self::$title = $title;
    }

    public static function getTitle()
    {
        return self::$title ;
    }

    public static function setContent($content)
    {
        self::$content = $content;
    }

    public static function setIgnoreRegex($regex = [])
    {
        $regex = is_array($regex) ? $regex : [$regex];
        self::$ignoreRegex = array_merge(self::$ignoreRegex, $regex);
    }
    
    /**
     * 记录日志
     * @param $project_id
     * @param $task_id
     * @param string $title
     * @param string $content
     * @param int $type
     * @return Log|void
     */
    public static function record($project_id,$task_id,$title = '', $content = '',$type=0, $create_type = 0, $service_client = '')
    {
        $auth = Auth::instance();
        $admin_id = $auth->isLogin() ? $auth->id : 0;
        $username = $auth->isLogin() ? $auth->username : __('Unknown');

        $controllername = Loader::parseName(request()->controller());
        $actionname = strtolower(request()->action());
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        if (self::$ignoreRegex) {
            foreach (self::$ignoreRegex as $index => $item) {
                if (preg_match($item, $path)) {
                    return;
                }
            }
        }

        $content = $content ? $content : self::$content;

        if (!$content) {
            $content = request()->param('', null, 'trim,strip_tags,htmlspecialchars');
            $content = self::getPureContent($content);
        }
        $title = $title ? $title : self::$title;
        if (!$title) {
            $title = [];
            $breadcrumb = Auth::instance()->getBreadcrumb($path);
            foreach ($breadcrumb as $k => $v) {
                $title[] = $v['title'];
            }
            $title = implode(' / ', $title);
        }
		if (is_array($content)&&$content){
            //字段处理
            $fieldModel=$task_id?new \app\admin\model\workteam\Task():new \app\admin\model\workteam\Project();


            foreach ($content as $k => &$v) {
                $listsMothod='get'.ucfirst($k)."List";
                if (method_exists($fieldModel, $listsMothod)) {
                    $templists=$fieldModel->$listsMothod();
                    $v=isset($templists[$v])?$templists[$v]:$v;
                }
                if (strpos($k, '_time') !== false) {
                    $v = datetime($v);
                }
            }
        }

		$content = !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content;
		$content_text = $create_type == 1 ? request()->input(['content_text'=>$content],'content_text',null,'trim,strip_tags,htmlspecialchars_decode') : $content;

		$res = self::create([
			'title'     => $title,
			'content'   => !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content,
			'content_text' => $content_text,
			'url'       => substr(request()->url(), 0, 1500),
			'admin_id'  => $admin_id,
			'username'  => $username,
			'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
			'ip'        => request()->ip(),
			'project_id'=>$project_id,
			'task_id'=>$task_id,
			'type'=>$type,
			'create_type'=>$create_type,
		]);
		return $res;
    }

    /**
     * 获取已屏蔽关键信息的数据
     * @param $content
     * @return false|string
     */
    protected static function getPureContent($content)
    {
        if (!is_array($content)) {
            return $content;
        }
        foreach ($content as $index => &$item) {
            if (preg_match("/(password|salt|token|price|expenses)/i", $index)) {
                $item = "***";
            } else {
                if (is_array($item)) {
                    $item = self::getPureContent($item);
                }
            }
        }
        return $content;
    }

    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id')->setEagerlyType(0);
    }


    public function getTypeList()
    {
//        return ['0' => __('客情记录'),'1' => __('更变'), '2' => __('催促'), '3' => __('留言'),'4' => __('自动')];
        return ['1' => __('更变'), '2' => __('催促'), '3' => __('留言'),'0' => __('自动')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

	public function getCreateTypeList()
	{
		return ['0' => __('自动'), '1' => __('手动')];
	}

	public function getCreateTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['create_type'];
        $list = $this->getCreateTypeList();
        return isset($list[$value]) ? $list[$value] : '';
	}

	public function getServiceClientTextAttr($value, $data){
		$value = $value ? $value : (isset($data['service_client']) ? $data['service_client'] : '');

		$client_data = [];
		if($value!=''){
			$clients = get_addon_config('facrm')['service_client'];
			$client_arr = explode(',', $value);
			foreach ($client_arr as $k => $v) {
				$client_data[] = isset($clients[$v]) ? $clients[$v] : '';
			}
		}
        return implode(',', $client_data);
	}
}
